package com.aliengen.thingple.driverapp.network.volley;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class Network {
    public static final String TAG = Network.class.getSimpleName();

    private static Network network = null;
    private Context context;
    private RequestQueue mRequestQueue;

    private Network(Context ctx)
    {
        context = ctx;
    }

    public static Network getInstance(Context ctx)
    {
        if(network == null) {
            network = new Network(ctx);
        }
        return network;
    }

    /**
     * Get the network request queue.
     *
     * @return RequestQueue
     */
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context, 10 * 1024 * 1024); // 10MB cache
        }

        return mRequestQueue;
    }

    /**
     * Add to the request queue.
     *
     * @param req
     * @param tag
     * @param <T>
     */
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    /**
     * Add to the request queue.
     *
     * @param req
     * @param <T>
     */
    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    /**
     * Cancel the pending requests by tag.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
